package com.example.quizamination.ui.main

import android.os.Bundle
import android.widget.TextView
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.GrantPermissionRule
import com.example.quizamination.MainActivity
import com.example.quizamination.R
import org.hamcrest.Matchers.*
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class MainFragmentUITest {

    @get:Rule
    val activityRule = ActivityScenarioRule(MainActivity::class.java)

    @Test
    fun testQuestionsListDisplayed() {
        val scenario = ActivityScenario.launch(MainActivity::class.java)

        scenario.onActivity { activity ->
            val fragment = MainFragment()

            activity.supportFragmentManager.beginTransaction()
                .replace(android.R.id.content, fragment)
                .commitNow()

            activity.supportFragmentManager.executePendingTransactions()
        }
        onView(withId(R.id.questionsListView)).check(matches(isDisplayed()))
    }

    @Test
    fun testNavigateToMainFragment() {
        onView(withId(R.id.nextButton)).perform(click())
        onView(withId(R.id.questionsListView)).check(matches(isDisplayed()))
    }

    @Test
    fun testAnimationOnResultFragment() {
        val resultText = "You have completed the quiz!"
        val fragmentArgs = Bundle().apply {
            putString("resultText", resultText)
        }

        launchFragmentInContainer<ResultFragment>(fragmentArgs)

        onView(withId(R.id.resTextView)).check(matches(withText(resultText)))

        onView(withId(R.id.repeatButton)).check(matches(isDisplayed()))
        onView(withId(R.id.repeatButton)).check(matches(isClickable()))
    }

}
